const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const apiMocker = require('webpack-api-mocker');
const pkg = require('./package.json');
const commonConfig = require('./webpack.common.config.js');

const devConfig = {
  entry: {
    app: [
      'react-hot-loader/patch',
      // react-hot-loader preserve component state
      path.join(__dirname, 'src/app.js'),
    ],
  },
  output: {
    publicPath: '/',
    path: path.join(__dirname, './dist'),
    filename: '[name].[hash].js', // 如果hash改成chunkhash，会报错 和webpack-dev-server --hot不兼容
    // 异步加载的模块是要以文件形式加载，生成的文件名是以chunkname配置的
    chunkFilename: '[name].chunk.[chunkhash].js',
  },
  devServer: {
    host: '0.0.0.0',
    port: 8080,
    contentBase: path.join(__dirname, './dist'),
    historyApiFallback: true,
    inline: true,
    before(app) {
      apiMocker(app, path.resolve('./mock/index.js'));
    },
  },
  module: {
    loaders: [{
      // less依赖
      test: /\.less$/,
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        {
          loader: 'less-loader',
          options: {
            javascriptEnabled: true,
            modifyVars: pkg.theme,
          },
        },
      ],
      include: path.resolve(__dirname, 'node_modules'),
    }, {
      // .less代码
      test: /\.less$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          options: {
            modules: true, // 开启css-module模式
            localIdentName: '[name]__[local]-[hash:base64:5]', // css类名规则
          },
        },
        'postcss-loader',
        'less-loader',
      ],
      include: path.resolve(__dirname, 'src'),
    }, {
      test: /\.scss$/,
      // style-loader：将所有的计算后的样式加入页面中
      // css-loader：你能够使用类似@import 和 url(...)的方法实现 require()的功能；
      // postcss-loader：用js来解析css成ast(抽象语法树)，它的插件可以处理很多你不必处理的乏味工作
      // 但需要配置postcssrc.js
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          options: {
            modules: true, // 开启css-module模式
            localIdentName: '[name]__[local]-[hash:base64:5]', // css类名规则
          },
        },
        'postcss-loader',
        'sass-loader',
      ],
      include: path.resolve(__dirname, 'src'),
    }],
  },
  plugins: [
    new webpack.EnvironmentPlugin({
      NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
      BABEL_ENV: 'development',
    }),
  ],
  devtool: 'inline-source-map',
}
module.exports = merge(commonConfig, devConfig)
